package com.sc.VenusQueryBeta.ui.fragments.vip.child;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hengjun.kingstar.sdk.MessageEvent;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.rxbus.RxBus;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.hengjun.kingstar.sdk.widgets.TipHelper;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.VipServiceAdapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.vip.VipUserContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.AccountList;
import com.sc.VenusQueryBeta.model.bean.account.List;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.model.sqlite.DataBaseDao;
import com.sc.VenusQueryBeta.model.sqlite.MsgListBean;
import com.sc.VenusQueryBeta.presenter.vip.VipUserPresenter;
import com.sc.VenusQueryBeta.ui.fragments.vip.VipRootFragment;
import com.sc.VenusQueryBeta.ui.widgets.HeaderAndFooterRecyclerViewAdapter;
import com.sc.VenusQueryBeta.ui.widgets.TimeCountUtil;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by Administrator on 21/9/2018.
 * 贵宾服务首页账户列表
 */

public class VipUserFragment extends BaseMVPCompatFragment<VipUserContract.VipUserPresenter> implements VipUserContract.IVipView {

    @BindView(R.id.setting_name)
    TextView settingName;
    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    //    @BindView(R.id.toolbar)
//    Toolbar toolbar;
//    @BindView(R.id.setting_title)
//    AppBarLayout settingTitle;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.tv_msg_count)
    TextView tvMsgCount;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.ll_vip)
    LinearLayout llVip;
    @BindView(R.id.rv_vip_list)
    RecyclerView rvVipList;

    private PopupWindow popupWindow;
    private UsersLoginBean loginBean;
    private boolean isUpdate = false;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter;
    private static final int REQUEST_COUNT = 10;

    private AccountList mqueryRegisBean;
    private VipServiceAdapter vipServiceAdapter;
    private QueryRegisBean mqueryregisbean;
    private int clientindex;
    private Object accountList;
    private Button send;
    private EditText hukoucomfitr;
    private EditText hukounewpwd;
    private EditText hukoucode;
    private String clientid;
    private View contentView;
    private CompositeDisposable compositeDisposable;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;
    private TextView confirm;
    private TextView back;
    private EditText pwd;
    private View contentView1;
    private PopupWindow popupWindow1;
    private int result;
    private DataBaseDao dataBaseDao;
    private IntentFilter intentFilter;
    private RedPointReceiver localReceiver;
    private String test1;
    private ArrayList<String> strings;
    private TimeCountUtil timeCountUtil;
    private List maccountAccountListBean;
    private List.Clients clients;

    public static VipUserFragment newInstance() {
        return new VipUserFragment();
    }

    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
//            mActivity.setIsTransAnim(false);
            mActivity.finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
//                ToastUtils.showToast(R.string.press_again);
            ToastUtils.showToast(getString(R.string.exit_again));
        }

        return true;
    }


    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return VipUserPresenter.newInstance();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (compositeDisposable != null) {
            RxBus.rxBusUnbund(compositeDisposable);
        }
        if (localReceiver != null) {
            LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(localReceiver);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_vip_user;
    }

    /**
     * 初始化界面
     *
     * @param view
     * @param savedInstanceState
     */
    @SuppressLint("ResourceType")
    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        WindowManager wm = mActivity.getWindowManager();
        int height = wm.getDefaultDisplay().getHeight();
        LogUtil.e("height=========" + height);
//        toolbar.getBackground().setAlpha(200);
//        llVip.measure(0,0);
//        int height = llVip.getMeasuredHeight();
//        int width = llVip.getMeasuredWidth();
//        LogUtil.e("llVip====="+height+"                    "+width);
//        rlTitle.measure(0,0);
//              int h = rlTitle.getMeasuredHeight();
//              int d = rlTitle.getMeasuredWidth();
//              LogUtil.e("rlTitle============"+h+"                          "+d);
        // inputOtherPwdWindow();
        LogUtils.e("initUI");
        //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
        vipServiceAdapter = new VipServiceAdapter(R.layout.item_vip_service);
        if (rvVipList != null) {
            rvVipList.setAdapter(vipServiceAdapter);
            rvVipList.setLayoutManager(new LinearLayoutManager(mActivity));

        }

        compositeDisposable = new CompositeDisposable();
        initInputPwdView();

        intentFilter = new IntentFilter();
        intentFilter.addAction("com.nyl.orderlybroadcast.VisibleReceiver");
        localReceiver = new RedPointReceiver();
        //注册本地接收器
        LocalBroadcastManager.getInstance(mActivity).registerReceiver(localReceiver, intentFilter);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();


        RxBus.getInstance().toObservableSticky(MessageEvent.class)
                .subscribe(new Observer<MessageEvent>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(MessageEvent setShoppingGoodsCount) {
                        LogUtils.e(" VipUserFragment onSupportVisible");
                        if (setShoppingGoodsCount.getMessage().equals("123")) {
                            setShoppingGoodsCount.setMessage("321");
                            FragmentManager fragmentManager = getFragmentManager();
                            if (fragmentManager != null) {
                                int count = fragmentManager.getBackStackEntryCount();
                                LogUtils.e("count=" + count);
                                if (count >= 1) {
                                    LogUtils.e("count >= 1");
                                    for (int i = 0; i < count; ++i) {
                                        fragmentManager.popBackStack();
                                    }
                                    startWithPop(VipRootFragment.newInstance());
                                } else {
                                    LogUtils.e("count<1");
                                    startWithPop(VipRootFragment.newInstance());
                                }
                            }
//                            StatusBarUtils.setColor(mActivity, getColor(R.color.theme_color));
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

//        RxBus.getInstance().toObservable(PusReadNumEvent.class)
//                .subscribe(new Observer<PusReadNumEvent>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        compositeDisposable.add(d);
//                    }
//
//                    @Override
//                    public void onNext(PusReadNumEvent setShoppingGoodsCount) {
//
//                        if (loginBean != null) {
//                            if (setShoppingGoodsCount.getName().equals("open")) {
//                                tvMsgCount.setVisibility(View.VISIBLE);
//                            } else {
//                                tvMsgCount.setVisibility(View.GONE);
//
//                            }
//                        }
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
//        //查询数据库看看是否存在未读消息
        if (loginBean != null) {
            dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
            java.util.List<MsgListBean> msgListBeans = dataBaseDao.searchAllRead();
            for (int i = 0; i < msgListBeans.size(); i++) {
//                if (msgListBeans.get(i).getIsRead().equals("0")) {
//                    tvMsgCount.setVisibility(View.VISIBLE);
//                }
                strings = new ArrayList<>();
                strings.add(msgListBeans.get(i).getIsRead());
                LogUtil.e("msgListBeans.get(i).getIsRead()=" + msgListBeans.get(i).getIsRead());
                if (strings.get(0).equals("0") && tvMsgCount != null) {
                    tvMsgCount.setVisibility(View.VISIBLE);
                    Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
                    //发送本地广播
                    LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
                    break;
                } else {
//                    tvMsgCount.setVisibility(View.GONE);
                }
                strings.clear();
            }
        } else {
            if (tvMsgCount != null) {
                tvMsgCount.setVisibility(View.GONE);
            }
        }

        boolean isMsgBack = SpUtils.getBoolean(MyApplication.app, Constants.MSG_BACkGROUND1, false);//后台收到通知 然后没有从通知栏打开 而是点击app的情况之下
        if (isMsgBack) {
            if (tvMsgCount != null) {
                tvMsgCount.setVisibility(View.VISIBLE);
                SpUtils.putBoolean(MyApplication.app, Constants.MSG_BACkGROUND1, false);
            }
        }

//        //通知main
//        Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
//        intentx.putExtra(Constants.CLOSE_RED, "close");
//        //发送本地广播
//        LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);

//        ToastUtils.showToast("woshivipuserfragment");

//        if (SpUtils.getBoolean(MyApplication.app, Constants.ACCEPT_NOTI_NOT_CLICK_MSG1, false)) {//查看通知是否被消灭
//            tvMsgCount.setVisibility(View.VISIBLE);
//        } else {
//            tvMsgCount.setVisibility(View.GONE);
//            ToastUtils.showToast("12121212121212");
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        boolean isMsgBack = SpUtils.getBoolean(MyApplication.app, Constants.MSG_BACkGROUND1, false);//后台收到通知 然后没有从通知栏打开 而是点击app的情况之下
        if (isMsgBack) {
            if (tvMsgCount != null) {
                tvMsgCount.setVisibility(View.VISIBLE);
                LogUtil.e("收到onresume");
                SpUtils.putBoolean(MyApplication.app, Constants.MSG_BACkGROUND1, false);
            } else {
                LogUtil.e("收到onresume but is null");
            }
        }


    }

    @SuppressLint("WrongConstant")
    private void initInputPwdView() {
        contentView1 = LayoutInflater.from(mActivity).inflate(R.layout.pop_input_pwd, null);
        if (popupWindow1 == null) {
            popupWindow1 = new PopupWindow(contentView1, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindow1.setTouchable(true);
        popupWindow1.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow1.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow1.getContentView().setFocusableInTouchMode(true);
        popupWindow1.getContentView().setFocusable(true);
        //这句话，让pop覆盖在输入法上面
        popupWindow1.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow1.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow1.setAnimationStyle(R.style.mypopwindow_anim_style);//设置弹出动画

        confirm = contentView1.findViewById(R.id.tv_true);
        back = contentView1.findViewById(R.id.tv_back);
        pwd = contentView1.findViewById(R.id.et_password);
        //點擊確認密碼
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwd.getText().toString().trim().equals("")) {
                    pwd.getText().clear();
                    pwd.setHint(R.string.pwd_not_null);
                    InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.toggleSoftInput(
                                InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
                    }
                } else {
                    showProgressDialog(getString(R.string.waiting));
                    LogUtil.e("pwd=" + pwd.getText().toString());
                    mPresenter.conFirmPwd(mqueryregisbean.getServerSetting().getServerAddress(), mqueryregisbean.getServerSetting().getServerProject(),
                            mqueryregisbean.getServerSetting().getServerPort(), pwd.getText().toString().trim(), clientid);
                }
            }

        });
    }

    /**
     * 設置密碼窗口
     */
    @SuppressLint("WrongConstant")
    private void inputOtherPwdWindow() {
        mqueryregisbean = SpUtils.getObject(MyApplication.getContext(), QueryRegisBean.class);
        contentView = LayoutInflater.from(mActivity).inflate(R.layout.custom_dialog_vip_pwd, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        //这句话，让pop覆盖在输入法上面
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);//设置弹出动画


        send = contentView.findViewById(R.id.hukou_send);
        hukoucomfitr = contentView.findViewById(R.id.hukou_comfiir_pwd);
        hukounewpwd = contentView.findViewById(R.id.hukou_newpwd);
        hukoucode = contentView.findViewById(R.id.hukou_code);
        Button button = contentView.findViewById(R.id.btn_complete);


        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (timeCountUtil != null && send != null) {
                    timeCountUtil.cancel();
                    timeCountUtil.onFinish();
                }
                hideSoftInput();
            }
        });
        //点击完成
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!hukoucomfitr.getText().toString().trim().equals("") || !hukounewpwd.getText().toString().trim().equals("") || !hukoucode.getText().toString().trim().equals("")) {
                    if (!hukoucode.getText().toString().trim().equals("") && hukounewpwd.getText().toString().trim().equals(hukoucomfitr.getText().toString().trim())) {
                        showProgressDialog(getString(R.string.settingnow));
                        mPresenter.sethukoupwd(clientindex, hukoucode.getText().toString(), hukounewpwd.getText().toString(), mqueryregisbean.getServerSetting().getServerSettingIndex() + "");
                    } else {
                        ToastUtils.showToast(getString(R.string.not_yiy));
                    }
                } else {
                    ToastUtils.showToast(getString(R.string.null_pwd));
                }
                InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }

        });
        //点击发送验证码
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //完成才調用
//                if (send.isFinish()) {
                showProgressDialog(getString(R.string.now_loading));
                mPresenter.sendcode(clientindex);
//                } else {
//                    ToastUtils.showToast("別著急哦");
//                }

            }
        });
    }

    protected void hideSoftInput() {
        View v = mActivity.getCurrentFocus();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = false;
            if (manager != null) {
                isOpen = manager.isActive();
            }
            if (isOpen) {
                manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        super.initData();
        LogUtils.e("initData");
        loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
        mqueryregisbean = SpUtils.getObject(MyApplication.getContext(), QueryRegisBean.class);
        reFreshListener();//下拉刷新監聽
    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mActivity);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (loginBean != null && ptrClass != null) {
                            isUpdate = true;
//                            ToastUtils.showToast("下拉刷新");
                            showProgressDialog(getString(R.string.loading));
                            mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取注册服务器
                            ptrClass.refreshComplete();
                        }
                    }
                }, 1000);
            }
        });
        //錯誤佈局點擊事件
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (loginBean != null) {//已经登录
//                    if (mqueryregisbean != null && mqueryregisbean.getServerSetting() != null) {//有端口
//                        vipServiceAdapter.setEmptyView(loadingView);
//                        mPresenter.queryAccountList(mqueryregisbean.getServerSetting().getServerAddress(), mqueryregisbean.getServerSetting().
//                                getServerProject(), mqueryregisbean.getServerSetting().getServerPort(), loginBean.getId());//2获取账户列表  //host serverProject  serverPort loginid
//
//                    } else {
//                        showProgressDialog("正在加載...");
//                        mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取查询注册服务器
//                    }
//                }
//            }
//        });
//        //空佈局點擊事件
//        emptyView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showProgressDialog("正在加載...");
//                mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取查询注册服务器
//            }
//        });
    }


//    private void inputMyPwdWindow(String s) {
//
////        DialogUIUtils.showAlert(mActivity, "請輸入戶口密碼", "", "请输入用户名", s, "返回", "確認", false, true, true, new DialogUIListener() {
////
////            @Override
////            public void onPositive(CharSequence input1, CharSequence input2) {
////
////            }
////
////            @Override
////            public void onNegative(CharSequence input1, CharSequence input2) {//确认
////                if (input2.toString().equals("")) {
////                    inputMyPwdWindow("密码不能为空！");
////                } else {
////                    showProgressDialog("请稍等...");
////                    mPresenter.conFirmPwd(mqueryregisbean.getServerSetting().getServerAddress(), mqueryregisbean.getServerSetting().getServerProject(), mqueryregisbean.getServerSetting().getServerPort(), input2.toString().trim(), clientid);
////                }
////            }
////
////            @Override
////            public void onGetInput(CharSequence input1, CharSequence input2) {
////
////            }
////        }).show();
//    }

    /**
     * 輸入本人戶口密碼窗口
     */
    @SuppressLint("WrongConstant")
    private void inputMyPwdWindow() {

        // 设置弹出窗体的背景
        popupWindow1.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow1.setBackgroundDrawable(cd);


        //點擊返回關閉彈窗
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow1.dismiss();
            }
        });


        popupWindow1.showAtLocation(contentView1.findViewById(R.id.ll_input_pop),
                Gravity.CENTER, 0, 0);

    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        LogUtils.e("onLazyInitView");
        if (loginBean != null) {//已经登录
            if (mqueryregisbean != null && mqueryregisbean.getServerSetting() != null) {//有端口
                mPresenter.queryAccountList(mqueryregisbean.getServerSetting().getServerAddress(), mqueryregisbean.getServerSetting().
                        getServerProject(), mqueryregisbean.getServerSetting().getServerPort(), loginBean.getId());//2获取账户列表  //host serverProject  serverPort loginid
                LogUtils.e("手机号码=============" + loginBean.getId());
            } else {
                mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取查询注册服务器
            }
        }

        inputOtherPwdWindow();

    }

//    @Override
//    protected void onErrorViewClick(View view) {
//        mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取查询注册服务器
//    }

//    @Override
//    protected void showLoading() {
//        LogUtils.e("showLoading");
//        vipServiceAdapter.setEmptyView(loadingView);
//    }

    /**
     * 获取查询注册服务器成功
     *
     * @param queryRegisBean
     */
    @Override
    public void showQueryRegisBeanDataSuccess(QueryRegisBean queryRegisBean) {
        if (queryRegisBean != null && queryRegisBean.getServerSetting() != null) {
            LogUtils.e("kaska" + queryRegisBean.getServerSetting().getServerAddress());
            SpUtils.putObject(MyApplication.getContext(), queryRegisBean);//保存取查询注册服务器成功返回的数据
            showProgressDialog(getString(R.string.loading));
            mPresenter.queryAccountList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), loginBean.getId());//2获取账户列表  //host serverProject  serverPort loginid
        } else {
//            if (queryRegisBean != null && queryRegisBean.getServerSetting() !=null) {
            if (ptrClass != null && tvEmpty != null) {
//                LogUtil.e("yigaixianshiwujilu");
//                ptrClass.setVisibility(View.VISIBLE);
//                tvEmpty.setVisibility(View.GONE);
//            }
//
//        } else {
//            if (ptrClass != null && tvEmpty != null) {
//
                rvVipList.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.VISIBLE);
            }
//        }
            hideProgressDialog();
//            vipServiceAdapter.setEmptyView(emptyView);
        }
    }

    /**
     * 填充账户列表适配器
     *
     * @param queryRegisBean
     */
    private void initRecycleView(final List queryRegisBean) {//R.layout.item_tjzx,
//        if (queryRegisBean != null && queryRegisBean.getClients() != null && queryRegisBean.getClients().size() > 0) {
//            if (ptrClass != null && tvEmpty != null) {
//                LogUtil.e("yigaixianshiwujilu");
//                ptrClass.setVisibility(View.VISIBLE);
//                tvEmpty.setVisibility(View.GONE);
//            }
//
//        } else {
//            if (ptrClass != null && tvEmpty != null) {
//
//                ptrClass.setVisibility(View.GONE);
//                tvEmpty.setVisibility(View.VISIBLE);
//            }
//        }
        mqueryregisbean = SpUtils.getObject(MyApplication.getContext(), QueryRegisBean.class);

        vipServiceAdapter = new VipServiceAdapter(R.layout.item_vip_service, queryRegisBean.getClients());
        ViewGroup.LayoutParams lp = rvVipList.getLayoutParams();
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        int height = dm.heightPixels;
        LogUtil.e("height=====" + height);
        if (queryRegisBean.getClients().size() <= 6) {
            if (height == 1280) {
                lp.height = DensityUtil.px2dip(120 * (queryRegisBean.getClients().size() + 2) * 2);
            } else {
                lp.height = DensityUtil.px2dip(120 * (queryRegisBean.getClients().size() + 2) * 4);
            }
//         lp.height = DensityUtil.px2dip(120 * (queryRegisBean.getClients().size() + 2) * 4);
        } else {
            if (height == 1280) {
                lp.height = DensityUtil.px2dip(120 * 8 * 2);
            } else {
                lp.height = DensityUtil.px2dip(120 * 8 * 4);
            }
//            lp.height = DensityUtil.px2dip(120 * 8 * 4);
        }
        vipServiceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {//监听列表点击
//                showProgressDialog(getString(R.string.list_footer_loading));
                clients = maccountAccountListBean.getClients().get(position);
                clientindex = Integer.parseInt(queryRegisBean.getClients().get(position).getClientindex());
                clientid = queryRegisBean.getClients().get(position).getClientid();
                LogUtils.e("clientid=====" + clientid);
                hideProgressDialog();
                //点击的时候先查询是否有账户密码
//                inputMyPwdWindow();
                showProgressDialog(getString(R.string.list_footer_loading));
                mPresenter.queryRegistPassword(Integer.parseInt(queryRegisBean.getClients().get(position).getClientindex()), mqueryregisbean.getServerSetting().getServerSettingIndex() + "");
                LogUtils.e("zhegezhishiduos=========" + mqueryregisbean.getServerSetting().getServerSettingIndex());
            }
        });

        if (rvVipList != null) {
            rvVipList.setAdapter(vipServiceAdapter);
        }
    }

    /**
     * 错误时回调
     */
    @Override
    public void showNetworkError() {
        hideProgressDialog();
//        vipServiceAdapter.setEmptyView(errorView);
    }

    /**
     * 获取账户列表成功
     *
     * @param accountAccountListBean accountAccountListBean
     */
    @Override
    public void showAccountListDataSuccess(List accountAccountListBean) {
        if (accountAccountListBean != null && accountAccountListBean.getClients() != null && accountAccountListBean.getClients().size() > 0) {
            if (ptrClass != null && tvEmpty != null) {
                LogUtil.e("yigaixianshiwujilu");
                ptrClass.setVisibility(View.VISIBLE);
                tvEmpty.setVisibility(View.GONE);
                maccountAccountListBean = accountAccountListBean;
            }
        } else {
            if (ptrClass != null && tvEmpty != null) {

                ptrClass.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.VISIBLE);
            }
        }
        if (accountAccountListBean != null && accountAccountListBean.getClients() != null) {
            initRecycleView(accountAccountListBean);
        } else {
            if (isUpdate) {//是下拉更新就替換當前數據
                isUpdate = false;
                if (accountAccountListBean != null && accountAccountListBean.getClients() != null) {
                    vipServiceAdapter.setNewData(accountAccountListBean.getClients());
                }
            } else {
                if (accountAccountListBean != null && accountAccountListBean.getClients() != null) {
                    vipServiceAdapter.addData(accountAccountListBean.getClients());
                }
            }
        }
        if (ptrClass != null) {
            ptrClass.refreshComplete();//
        }
        hideProgressDialog();
    }

    /**
     * 回調是否有賬戶密碼
     *
     * @param
     */
    @Override
    public void queryRegistPasswordBean(String queryRegistPasswordBean) {

        hideProgressDialog();
        if (queryRegistPasswordBean.equals("101")) {//已经有设置过账户密码  弹出 输入庄户密码窗口
            inputMyPwdWindow();
        } else {//没设置过密码  弹出 设置密码
            // 5 在底部显示
            if (hukoucode != null) {
                hukoucode.getText().clear();
            }
            if (hukoucomfitr != null) {
                hukoucomfitr.getText().clear();
            }
            if (hukounewpwd != null) {
                hukounewpwd.getText().clear();
            }
            popupWindow.showAtLocation(contentView.findViewById(R.id.rl_custom),
                    Gravity.CENTER, 0, 0);

        }
    }

    /**
     * 发送账户验证码回调成功
     *
     * @param sendcodeBean
     */
    @Override
    public void sendcodeBean(String sendcodeBean) {
        if (sendcodeBean.equals("400")) {//发送成功
            timeCountUtil = new TimeCountUtil(MyApplication.app, 120000, 1000, send);
            timeCountUtil.start();
//            send.start();
            hideProgressDialog();
            ToastUtils.showToast(getString(R.string.send_success));
            SpUtils.putString(MyApplication.app, Constants.VERTIFICATION_CODE, sendcodeBean);
            Timer timer = new Timer(true);
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    SpUtils.remove(MyApplication.app, Constants.VERTIFICATION_CODE);
//                      LogUtils.e("zoulezheli==========="+Constants.VERTIFICATION_CODE);
                }
            };
            timer.schedule(task, 600000);
        } else {//发送失败
            ToastUtils.showToast(getString(R.string.send_failed));
        }

    }


    /**
     * 设置密码回调成功
     *
     * @param sethukouBean
     */
    @Override
    public void sethukouBean(String sethukouBean) {
        if (sethukouBean.equals("200")) {//成功
            hideProgressDialog();
            ToastUtils.showToast(getString(R.string.setting_success));

//            if (send != null) {
//                if (!send.isFinish()) {
//                    send.cancel();
//                }
//            }
            popupWindow.dismiss();
        } else if (sethukouBean.equals("300")) {
            ToastUtils.showToast(getString(R.string.code_timeout));
            Animation shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);//加载动画资源文件
            hukoucode.startAnimation(shake);
            hukoucode.setText(getString(R.string.error_vertification_code));
            TipHelper.Vibrate(getActivity(), 1000);
            //振动验证码窗口
//            popupWindow.dismiss();
        } else if (sethukouBean.equals("301")) {
            ToastUtils.showToast(getString(R.string.code_error));
            hukoucode.getText().clear();
            hideProgressDialog();
//            popupWindow.dismiss();
        }
        hideProgressDialog();

    }

    /**
     * 输入密码 确认回调
     *
     * @param
     */
    @Override
    public void conFirmPwdBean(String s) {
        //密码正确
        if (s.equals("0")) {
            SpUtils.putInt(MyApplication.app, Constants.CLIENTINDEX, clientindex);
            InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.toggleSoftInput(
                        InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            }
            start(VipUserFragment2.newInstance(clientindex, mqueryregisbean, clientid,clients));
            pwd.getText().clear();
            pwd.setHint(getString(R.string.input_pwd));
            LogUtils.e("clientindex33=" + clientindex);
            if (popupWindow1 != null) {
                popupWindow1.dismiss();
            }
        } else if (s.equals("-1")) {//密码错误
            pwd.getText().clear();
            pwd.setHint(R.string.pwd_error);
            pwd.setFocusable(true);
        }
        hideProgressDialog();
    }


    @OnClick({R.id.iv_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_msg:
                start(MsgFragment.newInstance(), 2);
                break;
        }
    }


    //紅點更新
    public class RedPointReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //在这里写上相关的处理代码，一般来说，不要此添加过多的逻辑或者是进行任何的耗时操作
            //因为广播接收器中是不允许开启多线程的，过久的操作就会出现报错
            //因此广播接收器更多的是扮演一种打开程序其他组件的角色，比如创建一条状态栏通知，或者启动某个服务
            loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
            //查询数据库看看是否存在未读消息
            if (loginBean != null) {
                dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
                if (intent.getExtras() != null && tvMsgCount != null) {
                    if (intent.getExtras().getString(Constants.VISIBLE, "").equals(Constants.VISIBLE)) {//可见
                        tvMsgCount.setVisibility(View.VISIBLE);
                    }
                    if (intent.getExtras().getString(Constants.INVISIBLE, "").equals(Constants.INVISIBLE)) {//可见
                        tvMsgCount.setVisibility(View.INVISIBLE);
                    }
                }
            } else {
                if (tvMsgCount != null) {
                    tvMsgCount.setVisibility(View.GONE);
                }

            }

        }
    }
}